* Adjust overlapping event windows for countries with multiple episodes,
* ensuring that each observation is used in a single event.
* See Appendix A.B for details.

qui su episodeC
local max_epi=`r(max)'
local lessone = `max_epi' -1
forval i=1/`max_epi'{
gen overlap`i'=.
}
forval i=2/`max_epi'{
local j=`i'-1
gen DeltaPre`i'=.
replace DeltaPre`i' = normyearEpiC`j' - normyearEpiC`i'  if episode==`i' & normyearEpiC`i'!=. & normyearEpiC`j'!=.
gen cutoff_pre`i' = max(min(5-DeltaPre`i',-1),-4) if DeltaPre`i'!=.
replace overlap`i'=1 if normyearEpiC`i'<cutoff_pre`i' &  cutoff_pre`i' !=.
gen DeltaPost`j'=.
replace DeltaPost`j' = normyearEpiC`j' - normyearEpiC`i' if episode==`j' & normyearEpiC`i'!=. & normyearEpiC`j'!=.
gen cutoff_post`j' = max(min(DeltaPost`j'-1,5),DeltaPost`j'-4) if DeltaPost`j'!=. // at this year or later, we have overlap
replace overlap`j'=1 if normyearEpiC`j'>=cutoff_post`j' &  cutoff_post`j' !=.
}

* Set key variables as missing if there is overlap
forval i=1/`max_epi'{
	foreach var in relimportshare relimportshare2 relrer relrerPWT  relexportshare relrer_cpi relMIMD relMIMD2   {
	replace `var' = . if episode==`i' & overlap`i'!=.  & overlap`i'!=.  & overlap`i'==1
	}	
}

* Adjust post devaluation window for events that turn into large appreciations or when a new devaluation begins
foreach var in relimportshare relimportshare2 relrer relrerPWT  relexportshare relrer_cpi relMIMD relMIMD2  {
	replace `var' = . if ccode=="POL" & episode==2 & normyear>=4 // Turns into appreciation
	replace `var' = . if ccode=="ROM"  & normyear>=7 // New devaluation
	replace `var' = . if ccode=="SWE"  & normyear>=7 // New devaluation
	replace `var' = . if ccode=="MEX"  & episode==4 & normyear>=8 // New devaluation
	replace `var' = . if ccode=="ITA" & devaluationYear==1993  & normyear<=-4 // Pre-devaluation period overlaps with appreciation in 1986
}
